import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/company/company_add_user_edit_info/bean/company_add_user_edit_info_type.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/change_tab_event.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/refresh_company_detail_page_event.dart';
import 'package:e_reception_flutter/ui/create_user/create_user/bean/create_user_upload_bean.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/update_task_view_model.dart';
import 'package:e_reception_flutter/ui/person_detail/widgets/person_detail_invitation_tips_dialog/person_detail_invitation_tips_dialog.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'create_user_page.dart';

class CreateUserPageViewModel extends BaseViewModel {

  ///用户重复
  static final String _USER_REPEAT = "700";

  ///手机号重复
  static final String _PHONE_REPEAT = "701";

  VoidCallback onPushNameRepeat;

  CreateUserPageViewModel(BaseState state) : super(state){
    if(state is CreateUserPageState){
      onPushNameRepeat = state?.pushNameRepeatDialog;
    }
  }

  ///保存用户请求
  void saveUserHttp(BuildContext context, CreateUserUploadBean uploadBean,{bool showDialog=true}) async{
    if (uploadBean == null) {
      VgToastUtils.toast(context, "上传信息获取失败");
      return;
    }
    if(StringUtils.isNotEmpty(uploadBean?.phone) && !VgToolUtils.isPhone(uploadBean?.phone)){
      VgToastUtils.toast(context, "手机号不正确");
      return;
    }
    if(StringUtils.isNotEmpty(uploadBean?.phone) && !VgToolUtils.isPhone(uploadBean?.phone)){
      VgToastUtils.toast(context, "手机号不正确");
      return;
    }
    VgHudUtils.show(context,"保存中");
    if(StringUtils.isNotEmpty(uploadBean.headFaceUrl) && !VgStringUtils.isNetUrl(uploadBean.headFaceUrl)){
      try {
        String netFace = await VgMatisseUploadUtils.uploadSingleImageForFuture(
            uploadBean.headFaceUrl,isFace: true);
        if(StringUtils.isNotEmpty(netFace)){
          uploadBean.headFaceUrl = netFace;
        }else{
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "上传头像失败");
          return;
        }
      }catch(e){
        VgHudUtils.hide(context);

        VgToastUtils.toast(context, "上传头像失败");
        return;
      }
    }
    StringBuffer departmentManageIds=StringBuffer();
    if(uploadBean.departmentList!=null){
      uploadBean.departmentList.forEach((element) {departmentManageIds..write(element)..write(",");});
    }
    StringBuffer classIds=StringBuffer();
    if(uploadBean.classIdList!=null){
      uploadBean.classIdList.forEach((element) {classIds..write(element)..write(",");});
    }

    var params={
      "authId" : UserRepository.getInstance().authId ?? "",
      "groupid" : uploadBean?.groupBean?.groupid ?? "",
      "hsn":uploadBean.getHsnSplitStr() ?? "",
      "name": uploadBean?.name ?? "",
      "roleid": uploadBean?.getIdentityIdStr() ?? "",
      "city": uploadBean?.cityId ?? "",
      "classids": uploadBean?.classIds() ?? "",
      "companyid": UserRepository.getInstance().userData?.companyInfo?.companyid ?? "",
      "courseids":uploadBean?.courseIds() ?? "",
      // "createdate":
      // "createuid":
      // "delflg":
      "cbids":uploadBean?.cbid ?? "",
      "departmentid": uploadBean?.departmentId ?? "",
      // "fuid":
      "napicurl": uploadBean?.headFaceUrl ?? "",
      "nick":uploadBean?.nick ?? "",
      "number": uploadBean?.userNumber ?? "",
      "phone": globalSubPhone(uploadBean?.phone) ?? "",
      "projectid": uploadBean?.projectId ?? "",
      "putpicurl": uploadBean?.headFaceUrl ?? "",
      // "status"
      "type": "01",//用户状态00标记录入 01app手动添加
      // "userid":



    };
    if((uploadBean.departmentList??[]).isNotEmpty){
      String departmentId=departmentManageIds.toString();
      if(departmentId.endsWith(",")){
        departmentId=departmentId.substring(0,departmentId.length-1);
      }
      params["mDepartmentIds"]=departmentId;
    }
    if((uploadBean.classIdList??[]).isNotEmpty){
      String classIdList=uploadBean.classIdList.toString();
      if(classIdList.endsWith(",")){
        classIdList=classIdList.substring(0,classIdList.length-1);
      }
      params["mClassIds"]=classIds.toString();

    }

    VgHttpUtils.post(ServerApi.BASE_URL + "app/appAddUser",
        params: params,
        callback: BaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          BaseResponseBean bean = BaseResponseBean.fromMap(val);
          if(bean.code  == _USER_REPEAT || bean.code  == "702"){//702备注名重复
            if(onPushNameRepeat != null){
              onPushNameRepeat.call();
            }else{
              throw UnimplementedError();
            }
            return;
          }
          if(bean.code == _PHONE_REPEAT){
            VgToastUtils.toast(context, "用户已存在");
            return;
          }
          VgToastUtils.toast(context, "保存成功");
          VgEventBus.global.send(RefreshCompanyDetailPageEvent(msg:'新增员工'));
          VgEventBus.global.send(ChangeTabEvent(type: uploadBean?.groupBean?.groupType));
          RouterUtils.pop(context,result: true);
          if(showDialog??true){
            if(uploadBean?.headFaceUrl==null || uploadBean?.headFaceUrl==""){
              uploadBean?.fuid = bean?.data??"";//返回的fuid值
              if(UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition()){
                PersonDetailInvitationTipsDialog.navigatorPushDialog(AppMain.context,uploadBean);
              }
            }
            VgEventBus.global.send(PersonDetailGroupRefreshEvent());
          }
          VgEventBus.global.send(new MonitoringIndexPageClass());


        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }));
  }

  ///保存家长请求
  void saveParentUserHttp(BuildContext context, CreateUserUploadBean uploadBean,{bool showDialog=true}) async{
    if (uploadBean == null) {
      VgToastUtils.toast(context, "上传信息获取失败");
      return;
    }
    if(StringUtils.isNotEmpty(uploadBean?.phone) && !VgToolUtils.isPhone(uploadBean?.phone)){
      VgToastUtils.toast(context, "手机号不正确");
      return;
    }
    if(StringUtils.isNotEmpty(uploadBean?.phone) && !VgToolUtils.isPhone(uploadBean?.phone)){
      VgToastUtils.toast(context, "手机号不正确");
      return;
    }
    VgHudUtils.show(context,"保存中");
    if(StringUtils.isNotEmpty(uploadBean.headFaceUrl) && !VgStringUtils.isNetUrl(uploadBean.headFaceUrl)){
      try {
        String netFace = await VgMatisseUploadUtils.uploadSingleImageForFuture(
            uploadBean.headFaceUrl, isFace: true);
        if(StringUtils.isNotEmpty(netFace)){
          uploadBean.headFaceUrl = netFace;
        }else{
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "上传头像失败");
          return;
        }
      }catch(e){
        VgHudUtils.hide(context);

        VgToastUtils.toast(context, "上传头像失败");
        return;
      }
    }
    StringBuffer departmentManageIds=StringBuffer();
    String fuids="";
    if(uploadBean.departmentList!=null){
      uploadBean.departmentList.forEach((element) {departmentManageIds..write(element)..write(",");});
    }
    StringBuffer classIds=StringBuffer();
    if(uploadBean.classIdList!=null){
      uploadBean.classIdList.forEach((element) {classIds..write(element)..write(",");});
    }
    if(uploadBean?.relativeStuIds!=null && uploadBean?.relativeStuIds?.length !=0){
      fuids = VgStringUtils.getSplitStr(uploadBean?.relativeStuIds,symbol: ",");
    }
    var params={
      "authId" : UserRepository.getInstance().authId ?? "",
      "groupid" : uploadBean?.groupBean?.groupid ?? "",
      "name": uploadBean?.name ?? "",
      "fuids": fuids,
      "phone": globalSubPhone(uploadBean?.phone) ?? "",
      "picurl": uploadBean?.headFaceUrl ?? "",
      "cbids":uploadBean?.cbid ?? "",
    };

    VgHttpUtils.post(ServerApi.BASE_URL + "app/appAddParent",
        params: params,
        callback: BaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          BaseResponseBean bean = BaseResponseBean.fromMap(val);
          if(bean.code  == _USER_REPEAT){
            if(onPushNameRepeat != null){
              onPushNameRepeat.call();
            }else{
              throw UnimplementedError();
            }
            return;
          }
          if(bean.code == _PHONE_REPEAT){
            VgToastUtils.toast(context, "用户已存在");
            return;
          }
          VgToastUtils.toast(context, "保存成功");
          //02学员 03家长 04员工
          VgEventBus.global.send(new ChangeTabEvent(type: "03"));
          VgEventBus.global.send(RefreshCompanyDetailPageEvent(msg:'新增员工'));
          RouterUtils.pop(context,result: true);
          if(showDialog??true){
            if(uploadBean?.headFaceUrl==null || uploadBean?.headFaceUrl==""){
              uploadBean?.fuid = bean?.data??"";//返回的fuid值
              if(UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition()){
                PersonDetailInvitationTipsDialog.navigatorPushDialog(AppMain.context,uploadBean);
              }
            }
            VgEventBus.global.send(PersonDetailGroupRefreshEvent());
          }

        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }));
  }
}
